package servlets;

import beans.UseOrder;
import beans.Shenqing;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import service.UseOrderService;
import service.ShenqingService;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import jakarta.servlet.http.HttpSession;

@WebServlet("/UseOrderServlet")
public class UseOrderServlet extends HttpServlet {
    private UseOrderService useOrderService = new UseOrderService();
    private ShenqingService shenqingService = new ShenqingService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        UseOrderService orderService = new UseOrderService();
        if ("search".equals(action)) {
            // 获取搜索参数
            String orderId = req.getParameter("orderId");
            String employeeId = req.getParameter("employeeId");
            String status = req.getParameter("status");
            String startDate = req.getParameter("startDate");
            String endDate = req.getParameter("endDate");

            // 调用Service
            List<UseOrder> orders = orderService.searchOrders(
                    orderId, employeeId, status, startDate, endDate,1
            );
            req.setAttribute("orders", orders);
            req.getRequestDispatcher("/pirt/driversBig/All_Order.jsp").forward(req, resp);

        } else
        if ("search2".equals(action)) {
            // 获取搜索参数
            String orderId = req.getParameter("orderId");
            String employeeId = req.getParameter("employeeId");
            String status = req.getParameter("status");
            String startDate = req.getParameter("startDate");
            String endDate = req.getParameter("endDate");

            // 调用Service
            List<UseOrder> orders = orderService.searchOrders(
                    orderId, employeeId, status, startDate, endDate,0
            );
            req.setAttribute("orders", orders);
            req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp);

        } else if ("list".equals(action)) {
            // 获取所有已处理订单（自动过滤待审核）
            List<UseOrder> orders = orderService.getProcessedOrders();

            req.setAttribute("orders", orders);
            req.getRequestDispatcher("/pirt/driversBig/All_Order.jsp").forward(req, resp);
        } else if ("detail".equals(action)) {
            // 查看订单详情
            String orderId = req.getParameter("orderId");
            if (orderId != null && !orderId.isEmpty()) {
                try {
                    UseOrder order = orderService.getUseOrderById(orderId);
                    req.setAttribute("order", order);
                    req.getRequestDispatcher("/pirt/driversBig/OrderDetail.jsp").forward(req, resp);
                } catch (Exception e) {
                    e.printStackTrace();
                    req.setAttribute("error", "获取订单详情失败：" + e.getMessage());
                }
            } else {
                req.setAttribute("error", "订单ID不能为空");

            }
        } else if ("all2".equals(action))
        {
            List<UseOrder> orders = orderService.getOrders();
            req.setAttribute("orders", orders);
            req.getRequestDispatcher("/pirt/driversBig/My_Tasks.jsp").forward(req, resp);
        } else        if ("order".equals(action)) {
            req.getRequestDispatcher("pirt/driversBig/All_Order.jsp").forward(req, resp);
            System.out.println(67890);
        }

        // 历史订单查询（包含搜索功能）
        else if ("employeeOrders".equals(action)) {
            // 从session获取当前登录的员工ID
            Object employeeObj = req.getSession().getAttribute("user");
            if (employeeObj != null && employeeObj instanceof beans.Employee) {
                beans.Employee employee = (beans.Employee) employeeObj;
                int employeeId = employee.getEmployeeID();

                // 获取搜索参数
                String searchOrderId = req.getParameter("orderId");

                if (searchOrderId != null && !searchOrderId.trim().isEmpty()) {
                    // 按订单号搜索
                    boolean orderExists = useOrderService.orderExists(searchOrderId.trim());

                    if (orderExists) {
                        // 订单存在于use_order表中
                        UseOrder order = useOrderService.getOrderById(searchOrderId.trim());

                        if (order != null && order.getEmployeeId() == employeeId) {
                            // 将单个订单包装成列表
                            List<UseOrder> orders = new ArrayList<>();
                            orders.add(order);
                            req.setAttribute("orders", orders);
                            req.setAttribute("searchResult", "found");
                        } else {
                            req.setAttribute("orders", Collections.emptyList());
                            req.setAttribute("errorMessage", "您无权查看此订单信息或订单不存在");
                        }
                    } else {
                        // 检查是否在shenqing表中
                        boolean shenqingExists = shenqingService.shenqingExists(searchOrderId.trim());

                        if (shenqingExists) {
                            Shenqing shenqing = shenqingService.getShenqingById(searchOrderId.trim());

                            if (shenqing != null && shenqing.getEmployeeId() == employeeId) {
                                req.setAttribute("orders", Collections.emptyList());
                                req.setAttribute("shenqingResult", shenqing);
                                req.setAttribute("searchResult", "reviewing");
                            } else {
                                req.setAttribute("orders", Collections.emptyList());
                                req.setAttribute("errorMessage", "您无权查看此订单信息或订单不存在");
                            }
                        } else {
                            req.setAttribute("orders", Collections.emptyList());
                            req.setAttribute("errorMessage", "未找到订单号为 " + searchOrderId + " 的订单");
                        }
                    }
                    req.setAttribute("searchOrderId", searchOrderId);
                } else {
                    // 获取该员工的所有历史订单
                    List<UseOrder> orders = useOrderService.getOrdersByEmployeeId(employeeId);
                    req.setAttribute("orders", orders);
                }

                req.getRequestDispatcher("/lishi.jsp").forward(req, resp);
            } else {
                // 未登录或session中没有员工信息
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
            }
        }

        // 申请进度查询（直接显示最新订单）
        else if ("progress".equals(action)) {
            // 处理进度查询请求 - 支持搜索和显示最新订单
            Object employeeObj = req.getSession().getAttribute("user");

            if (employeeObj != null && employeeObj instanceof beans.Employee) {
                beans.Employee employee = (beans.Employee) employeeObj;
                int employeeId = employee.getEmployeeID();

                // 获取搜索参数
                String searchOrderId = req.getParameter("orderId");

                if (searchOrderId != null && !searchOrderId.trim().isEmpty()) {
                    // 按订单号搜索 - 与历史订单页面相同的逻辑
                    boolean orderExists = useOrderService.orderExists(searchOrderId.trim());

                    if (orderExists) {
                        // 订单存在于use_order表中
                        UseOrder order = useOrderService.getOrderById(searchOrderId.trim());

                        if (order != null && order.getEmployeeId() == employeeId) {
                            req.setAttribute("order", order);
                            req.setAttribute("orderStatus", "processed");
                        } else {
                            req.setAttribute("orderStatus", "none");
                            req.setAttribute("errorMessage", "您无权查看此订单信息或订单不存在");
                        }
                    } else {
                        // 检查是否在shenqing表中
                        boolean shenqingExists = shenqingService.shenqingExists(searchOrderId.trim());

                        if (shenqingExists) {
                            Shenqing shenqing = shenqingService.getShenqingById(searchOrderId.trim());

                            if (shenqing != null && shenqing.getEmployeeId() == employeeId) {
                                req.setAttribute("shenqing", shenqing);
                                req.setAttribute("orderStatus", "reviewing");
                            } else {
                                req.setAttribute("orderStatus", "none");
                                req.setAttribute("errorMessage", "您无权查看此订单信息或订单不存在");
                            }
                        } else {
                            req.setAttribute("orderStatus", "none");
                            req.setAttribute("errorMessage", "未找到订单号为 " + searchOrderId + " 的订单");
                        }
                    }
                    req.setAttribute("searchOrderId", searchOrderId);
                } else {
                    // 没有搜索参数，显示最新订单
                    UseOrder order = useOrderService.getLatestOrderByEmployeeId(employeeId);

                    if (order != null) {
                        // 在use_order表中找到了最新订单
                        req.setAttribute("order", order);
                        req.setAttribute("orderStatus", "processed");
                    } else {
                        // 在use_order表中没有找到，尝试在shenqing表中查找最新申请
                        Shenqing latestShenqing = shenqingService.getLatestShenqingByEmployeeId(employeeId);

                        if (latestShenqing != null) {
                            req.setAttribute("shenqing", latestShenqing);
                            req.setAttribute("orderStatus", "reviewing");
                        } else {
                            // 没有找到任何订单或申请
                            req.setAttribute("orderStatus", "none");
                        }
                    }
                }

                req.getRequestDispatcher("/jindu.jsp").forward(req, resp);
            } else {
                // 未登录
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
            }
        }
        else{
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "请求的操作不存在");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        if ("add".equals(action)) {
            addOrder(req, resp);
        } else if ("update".equals(action)) {
            updateOrder(req, resp);
        } else if ("updateStatus".equals(action)) {
            updateOrderStatus(req, resp);
        } else if ("getOrderDetail".equals(action)) {
            getOrderDetail(req, resp);
        } else if ("assignOrder".equals(action)) {
            assignOrder(req, resp);
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "请求的操作不存在");
        }
    }

    private void addOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            UseOrder order = new UseOrder();
            // 设置订单属性
            order.setOrderId(req.getParameter("orderId"));
            order.setDriverId(Integer.parseInt(req.getParameter("driverId")));
            order.setVehicleId(Integer.parseInt(req.getParameter("vehicleId")));
            order.setPurpose(req.getParameter("purpose"));
            order.setDestination(req.getParameter("destination"));

            // 处理日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String startDateStr = req.getParameter("startDate");
            String endDateStr = req.getParameter("endDate");

            if (startDateStr != null && !startDateStr.isEmpty()) {
                order.setExpectedDepartureTime(sdf.parse(startDateStr));
            }
            if (endDateStr != null && !endDateStr.isEmpty()) {
                order.setExpectedReturnTime(sdf.parse(endDateStr));
            }

            boolean success = useOrderService.addUseOrder(order);
            if (success) {
                req.getSession().setAttribute("successMessage", "用车申请提交成功");
                resp.sendRedirect("All_Order.jsp");
            } else {
                req.setAttribute("error", "提交失败，请检查输入信息");
                req.getRequestDispatcher("add_order.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("error", "系统错误：" + e.getMessage());
            req.getRequestDispatcher("add_order.jsp").forward(req, resp);
        }
    }

    private void updateOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            UseOrder order = new UseOrder();
            // 设置订单属性
            order.setOrderId(req.getParameter("orderId"));
            order.setReviewStatus(req.getParameter("status"));
            order.setRemarks(req.getParameter("remarks"));

            boolean success = useOrderService.updateUseOrder(order);
            if (success) {
                req.getSession().setAttribute("successMessage", "订单状态更新成功");
                resp.sendRedirect("All_Order.jsp");
            } else {
                req.setAttribute("error", "更新失败，请检查输入信息");
                req.getRequestDispatcher("edit_order.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("error", "系统错误：" + e.getMessage());
            req.getRequestDispatcher("edit_order.jsp").forward(req, resp);
        }
    }

    private void updateOrderStatus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        
        String orderId = req.getParameter("orderId");
        String status = req.getParameter("status");
        String result;
        
        try {
            // 参数验证
            if (orderId == null || status == null) {
                result = "{\"success\":false,\"message\":\"参数不完整\"}";
                resp.getWriter().write(result);
                return;
            }
            
            // 验证状态值
            if (!"已完成".equals(status)) {
                result = "{\"success\":false,\"message\":\"无效的状态值\"}";
                resp.getWriter().write(result);
                return;
            }
            
            // 调用Service层更新状态
            boolean updated = useOrderService.updateOrderStatus(orderId, status);
            
            if (updated) {
                result = "{\"success\":true,\"message\":\"订单状态更新成功\"}";
            } else {
                result = "{\"success\":false,\"message\":\"订单状态更新失败，请确认订单状态为'已通过'\"}";
            }
        } catch (Exception e) {
            result = "{\"success\":false,\"message\":\"系统错误：" + e.getMessage().replace("\"", "\\\"") + "\"}";
        }
        
        resp.getWriter().write(result);
    }

    private void getOrderDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        
        String orderId = req.getParameter("orderId");
        StringBuilder result = new StringBuilder();
        
        try {
            UseOrder order = useOrderService.getOrderById(orderId);
            if (order != null) {
                result.append("{");
                result.append("\"success\":true,");
                result.append("\"order\":{");
                result.append("\"orderId\":\"").append(order.getOrderId()).append("\",");
                result.append("\"applicant\":\"员工").append(order.getEmployeeId()).append("\",");
                result.append("\"purpose\":\"").append(order.getUsageReason().replace("\"", "\\\"")).append("\",");
                result.append("\"destination\":\"").append(order.getDestination().replace("\"", "\\\"")).append("\",");
                result.append("\"useTime\":\"").append(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getExpectedDepartureTime())).append("\",");
                result.append("\"status\":\"").append(order.getReviewStatus().toLowerCase()).append("\",");
                result.append("\"statusText\":\"").append(order.getReviewStatus()).append("\"");
                result.append("}");
                result.append("}");
            } else {
                result.append("{");
                result.append("\"success\":false,");
                result.append("\"message\":\"未找到订单信息\"");
                result.append("}");
            }
        } catch (Exception e) {
            result.append("{");
            result.append("\"success\":false,");
            result.append("\"message\":\"系统错误：").append(e.getMessage().replace("\"", "\\\"")).append("\"");
            result.append("}");
        }
        
        resp.getWriter().write(result.toString());
    }

    private void assignOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单提交的参数
        String shenqingOrderIdStr = request.getParameter("orderId");
        String driverIdStr = request.getParameter("driverId");
        String vehicleIdStr = request.getParameter("vehicleId");
        String purpose = request.getParameter("purpose");
        String statusRemarks = "已分配司机和车辆";

        HttpSession session = request.getSession();
        Integer reviewerId = (Integer) session.getAttribute("employeeId");

        // 1. 参数验证
        if (shenqingOrderIdStr == null || shenqingOrderIdStr.isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/pirt/driversBig/AssignDriverAndVehicle.jsp?error=missing_order_id");
            return;
        }

        if (driverIdStr == null || driverIdStr.isEmpty() || vehicleIdStr == null || vehicleIdStr.isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/pirt/driversBig/AssignDriverAndVehicle.jsp?orderId=" + shenqingOrderIdStr + "&error=missing_driver_or_vehicle");
            return;
        }

        if (purpose == null || purpose.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/pirt/driversBig/AssignDriverAndVehicle.jsp?orderId=" + shenqingOrderIdStr + "&error=missing_purpose");
            return;
        }

        if (reviewerId == null) {
            response.sendRedirect(request.getContextPath() + "/pirt/driversBig/AssignDriverAndVehicle.jsp?orderId=" + shenqingOrderIdStr + "&error=invalid_reviewer");
            return;
        }

        try {
            int shenqingOrderId = Integer.parseInt(shenqingOrderIdStr);
            int driverId = Integer.parseInt(driverIdStr);
            int vehicleId = Integer.parseInt(vehicleIdStr);

            // 2. 检查申请是否存在且状态正确
            Shenqing shenqing = shenqingService.getShenqingById(String.valueOf(shenqingOrderId));
            if (shenqing == null) {
                response.sendRedirect(request.getContextPath() + "/pirt/driversBig/AssignDriverAndVehicle.jsp?orderId=" + shenqingOrderIdStr + "&error=shenqing_not_found");
                return;
            }

            if (!"待审核".equals(shenqing.getStatus())) {
                response.sendRedirect(request.getContextPath() + "/pirt/driversBig/AssignDriverAndVehicle.jsp?orderId=" + shenqingOrderIdStr + "&error=invalid_status");
                return;
            }

            // 3. 检查是否已经存在对应的用车订单
            if (useOrderService.orderExists(String.valueOf(shenqingOrderId))) {
                response.sendRedirect(request.getContextPath() + "/pirt/driversBig/AssignDriverAndVehicle.jsp?orderId=" + shenqingOrderIdStr + "&error=order_already_exists");
                return;
            }

            // 4. 创建用车订单
            UseOrder useOrder = new UseOrder();
            useOrder.setOrderId(String.valueOf(shenqing.getOrderId()));
            useOrder.setEmployeeId(shenqing.getEmployeeId());
            useOrder.setDriverId(driverId);
            useOrder.setVehicleId(vehicleId);
            useOrder.setExpectedDepartureTime(shenqing.getDepartureTime());
            useOrder.setExpectedReturnTime(shenqing.getReturnTime());
            useOrder.setRemarks(shenqing.getRemarks());
            useOrder.setUsageReason(shenqing.getUsageReason());
            useOrder.setPassengers(shenqing.getPassengers());
            useOrder.setReviewStatus("已通过");
            useOrder.setReviewer(reviewerId);
            useOrder.setPurpose(purpose);
            useOrder.setDestination(shenqing.getDestination());
            useOrder.setStatusremarks(statusRemarks);

            // 5. 保存订单并更新申请状态
            boolean insertSuccess = useOrderService.createUseOrderByShenqing(useOrder);
            if (insertSuccess) {
                boolean updateSuccess = shenqingService.updateShenqingStatus(shenqing);
                if (updateSuccess) {
                    response.sendRedirect(request.getContextPath() + "/pirt/driversBig/My_Tasks.jsp?status=assign_success");
                } else {
                    // 如果更新申请状态失败，需要回滚订单创建
                    useOrderService.deleteUseOrder(String.valueOf(shenqingOrderId));
                    response.sendRedirect(request.getContextPath() + "/pirt/driversBig/AssignDriverAndVehicle.jsp?orderId=" + shenqingOrderIdStr + "&error=update_status_failed");
                }
            } else {
                response.sendRedirect(request.getContextPath() + "/pirt/driversBig/AssignDriverAndVehicle.jsp?orderId=" + shenqingOrderIdStr + "&error=insert_failed");
            }

        } catch (NumberFormatException e) {
            response.sendRedirect(request.getContextPath() + "/pirt/driversBig/AssignDriverAndVehicle.jsp?orderId=" + shenqingOrderIdStr + "&error=invalid_number_format");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/pirt/driversBig/AssignDriverAndVehicle.jsp?orderId=" + shenqingOrderIdStr + "&error=internal_error");
        }
    }
}
